package wiki.liven.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by qiangjun on 2017/3/2.
 * 时间操作
 */
public class TimeUtils {

    public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 增加时间的小时数
     * @param srcTime 原时间
     * @param step 增加的小时数
     * @return 增加小时候的时间
     * @throws ParseException
     */
    public static String addHour(String srcTime,Integer step) throws ParseException {
        String resTime;
        Date srcDate = simpleDateFormat.parse(srcTime);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(srcDate);
        calendar.add(Calendar.HOUR_OF_DAY,step);
        resTime = simpleDateFormat.format(calendar.getTime());
        return resTime;
    }

    /**
     * 格式化时间为字符串
     * @param date
     * @return
     */
    public static String formatDate(Date date){
        String time = simpleDateFormat.format(date);
        return time;

    }


    /**
     * 分割时间
     * @param startTime
     * @param endTime
     * @param type 单位（天、周、月、年）->(day,week,month,year)
     * @return
     */
    public static List<String> slicedTime(String startTime,String endTime,String type) throws ParseException {
        List<String> times = new ArrayList<>();
        Date startDate = null;
        Date endDate = null;
        if ("day".equals(type)){
            startDate = simpleDateFormat.parse(startTime.concat(" 00:00:00"));
            endDate = simpleDateFormat.parse(endTime.concat(" 23:59:59"));
            endDate = add(endDate,"day");
        }
        if ("month".equals(type)){
            startDate = simpleDateFormat.parse(startTime.concat("-01-01 00:00:00"));
            endDate = simpleDateFormat.parse(endTime.concat("-12-31 23:59:59"));
            endDate = add(endDate,"month");
        }
        for (Date i = startDate;i.before(endDate);i = add(i,type)){
            times.add(simpleDateFormat.format(i));
        }
        return times;
    }


    /**
     * 时间自增，按照单位长度
     * @param date
     * @param type 天、周、月、年
     */
    private static Date add(Date date, String type) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        if("day".equals(type))
            calendar.add(Calendar.DAY_OF_YEAR,1);
        if ("week".equals(type))
            calendar.add(Calendar.WEEK_OF_YEAR,1);
        if ("month".equals(type))
            calendar.add(Calendar.MONTH,1);
        if ("year".equals(type))
            calendar.add(Calendar.YEAR,1);
        return calendar.getTime();
    }

}
